<template>
  <el-dialog
    title="修改密码"
    :visible.sync="visibleDialog"
    :close-on-click-modal="false"
    append-to-body
    width="450px"
  >
    <el-form ref="rowForm" :model="row" :rules="rules" label-width="80px">
      <el-form-item label="原始密码" prop="passwordOld">
        <el-input v-model="row.passwordOld" type="password" autocomplete="off" show-password />
      </el-form-item>
      <el-form-item label="新的密码" prop="passwordNew">
        <el-input v-model="row.passwordNew" type="password" autocomplete="off" show-password />
      </el-form-item>
      <el-form-item label="确认密码" prop="passwordConfirm">
        <el-input v-model="row.passwordConfirm" type="password" autocomplete="off" show-password />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="btnSaveLoading" @click="handleSave">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import UserApi from "@/api/UserApi"

export default {
  props: {
    open: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      btnSaveLoading: false,
      row: {
        passwordOld: null,
        passwordNew: null,
        passwordConfirm: null
      },
      rules: {
        passwordOld: [
          { required: true, message: "请输入原密码", trigger: "blur" },
          { min: 6, max: 15, message: "长度在 6 到 15 个字符", trigger: "blur" }
        ],
        passwordNew: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 15, message: "长度在 6 到 15 个字符", trigger: "blur" }
        ],
        passwordConfirm: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 15, message: "长度在 6 到 15 个字符", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback()
              }
              if (value === this.row.passwordNew) {
                callback()
              } else {
                callback(new Error("两次输入密码不一致"))
              }
            },
            trigger: "blur"
          }
        ]
      }
    }
  },
  computed: {
    visibleDialog: {
      get() {
        return this.open
      },
      set(val) {
        this.$emit("update:open", val)
      }
    }
  },
  methods: {
    handleCancel() {
      this.$refs.rowForm.resetFields()
      this.visibleDialog = false
    },
    handleSave() {
      this.$refs.rowForm.validate(valid => {
        if (valid) {
          this.btnSaveLoading = true
          UserApi.changePwd(this.row).then(() => {
            this.btnSaveLoading = false
            this.$message.success("密码修改成功")
            this.handleCancel()
            this.$emit("ok")
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>
